/*Hm9gUKDDwtNjV7Mk8onAzgXlk2sN3YqGeiNBfMPmEAaQ5tb/cjXQzjs3lVWuDzNj*/
import { ajax, print, output, cardCache } from 'nc-lightapp-front';
import { pageConfig } from '../const';
import searchBtnClick from './searchBtnClick';
import ampub from 'ampub';
const { components, commonConst, utils } = ampub;
const { StatusUtils, CommonKeys } = commonConst;
const { msgUtils, listUtils, multiLangUtils, getThemeUtils } = utils;
const { getMultiLangByID } = multiLangUtils;
const { showConfirm, MsgConst, showMessage } = msgUtils;
const { ScriptReturnUtils } = components;
const { getScriptListReturn } = ScriptReturnUtils;
const { UISTATE } = StatusUtils;
const { approveConst } = CommonKeys;
const { setBillFlowBtnsEnable, batchRefresh } = listUtils;
const {
	tableId,
	pagecode,
	pkField,
	url,
	printNodekey,
	cardRouter,
	btn_head,
	printFilename,
	dataSource,
	alarmId,
	alarmFlag
} = pageConfig;

/**
 * 按钮点击
 * @param {*} props 
 * @param {*} id 
 */
export default function buttonClick(props, id) {
	switch (id) {
		case btn_head.ADD:
			linkToCard.call(this, props, undefined, UISTATE.add);
			break;

		case btn_head.REFRESH:
			refreshAction.call(this, props);
			break;

		case btn_head.DELETE:
			batchDelete.call(this, props);
			break;

		case btn_head.COMMIT:
			commitAction.call(this, props, 'SAVE', null);
			break;

		case btn_head.UNCOMMIT:
			commitAction.call(this, props, 'UNSAVE', null);
			break;

		case btn_head.QUERYABOUTBUDGET:
			queryAboutBudgetAction.call(this, props);
			break;

		case btn_head.PRINT:
			printAction.call(this, props);
			break;

		case btn_head.OUTPUT:
			outputAction.call(this, props);
			break;

		case btn_head.COPY:
			copyAction.call(this, props, null);
			break;

		case btn_head.ATTACHMENT:
			attachmentAction.call(this, props);
			break;

		default:
			break;
	}
}

//审批详情
export function openApproveAction(props, row) {
	this.setState({
		showApprove: true,
		transi_type: row.values.transi_type.value,
		pk_newasset: row.values.pk_newasset.value
	});
}

//附件
function attachmentAction(props) {
	let checkedRows = props.table.getCheckedRows(tableId);
	if (!checkedRows || checkedRows.length == 0) {
		showMessage.call(this, props, { type: MsgConst.Type.ChooseOne });
		return;
	}
	// 单据编码
	let billNo = checkedRows[0].data.values['bill_code'].value;
	// 单据主键
	let billId = checkedRows[0].data.values[pkField].value;
	props.ncUploader.show(`${pagecode}-uploader`, {
		billId: 'fa/newasset/' + billId,
		billNo
	});
}

//复制
function copyAction(props, row) {
	let id = '';
	if (row == null) {
		let data = props.table.getCheckedRows(tableId);
		// 选择多条数据时，默认复制第一条
		if (data.length == 0) {
			showMessage.call(this, props, { type: MsgConst.Type.ChooseCopy });
			return;
		}
		id = data[0].data.values.pk_newasset.value;
	} else {
		id = row.values.pk_newasset.value;
	}
	props.pushTo(cardRouter, {
		status: UISTATE.browse,
		id,
		copyflag: true,
		pagecode: pagecode.replace('list', 'card')
	});
}

//表体复制
export function copyActionSignal(props, row) {
	copyAction(props, row);
}

//输出
function outputAction(props) {
	let printData = getPrintData.call(this, props, 'output');
	if (!printData) {
		showMessage.call(this, props, { type: MsgConst.Type.ChooseOutput });
		return;
	}
	output({
		url: url.PRINTCARD,
		data: printData
	});
}

//打印
function printAction(props) {
	let printData = getPrintData.call(this, props, 'print');
	if (!printData) {
		showMessage.call(this, props, { type: MsgConst.Type.ChoosePrint });
		return;
	}
	print(
		'pdf', // 支持两类：'html'为模板打印，'pdf'为pdf打印
		url.PRINTCARD, // 后台打印服务url
		printData
	);
}

/**
 * 获取打印数据
 * @param {*} props 
 * @param {*} outputType 
 */
function getPrintData(props, outputType = 'print') {
	let checkedRows = props.table.getCheckedRows(tableId);
	if (!checkedRows || checkedRows.length == 0) {
		return false;
	}
	let pks = [];
	checkedRows.map((item) => {
		pks.push(item.data.values.pk_newasset.value);
	});
	let printData = {
		filename: getMultiLangByID(printFilename), // 文件名称
		nodekey: printNodekey, // 模板节点标识
		oids: pks, // 需要打印数据主键
		outputType // 输出类型
	};
	return printData;
}

// 预算联查
function queryAboutBudgetAction(props) {
	let datas = props.table.getCheckedRows(tableId);
	if (datas.length == 0) {
		showMessage.call(this, props, { type: MsgConst.Type.ChooseOne });
		return;
	}
	let sourceData = null;
	let pk_newasset = datas[0].data.values.pk_newasset.value;
	ajax({
		url: url.QUERYABOUTBUDGET,
		data: {
			pk: pk_newasset
		},
		success: (res) => {
			if (res.data.hint != undefined) {
				showMessage.call(this, props, { color: 'warning', content: res.data.hint });
			} else {
				this.setState({
					show: true,
					sourceData: res.data
				});
			}
		}
	});
}

// 提交、收回
export function commitAction(props, OperatorType, rows, content, alarmPks) {
	let paramInfoMap = {};
	let params = [];
	//先判断是表肩批量提交还是表体按钮提交
	if (rows == null) {
		let data = props.table.getCheckedRows(tableId);
		if (data.length == 0) {
			showMessage.call(this, props, { type: MsgConst.Type.ChooseOne });
			return;
		}
		if (alarmPks) {
			for (let v of data) {
				if (alarmPks.has(v.data.values.pk_newasset.value)) {
					let id = v.data.values.pk_newasset.value;
					let ts = v.data.values.ts.value;
					let index = v.index;
					paramInfoMap[id] = ts;
					params.push({ id, index });
				}
			}
		} else {
			params = data.map((v) => {
				let id = v.data.values.pk_newasset.value;
				let ts = v.data.values.ts.value;
				let index = v.index;
				paramInfoMap[id] = ts;
				return {
					id,
					index
				};
			});
		}
	} else {
		params = rows.map((row) => {
			let id = row.values[pkField].value;
			let ts = row.values.ts.value;
			let index = row.index;
			paramInfoMap[id] = ts;
			return {
				id,
				index
			};
		});
	}

	let commitType = '';
	if (OperatorType === 'SAVE') {
		//提交传这个
		commitType = 'commit';
	}
	let listData = {
		paramInfoMap: paramInfoMap,
		dataType: 'listData',
		OperatorType: OperatorType,
		pageid: pagecode,
		commitType: commitType, //提交
		content: content,
		userMap: alarmPks && { fa_alarm: 'alarmContinue' }
	};
	ajax({
		url: url.COMMIT,
		data: listData,
		success: (res) => {
			if (content) {
				this.setState({
					compositedisplay: false
				});
			}
			//先判断是否有预警异常
			if (res.data && res.data.userMsgs && Object.keys(res.data.userMsgs).length > 0) {
				//先进行回显处理
				selfListReturn.call(this, params, res, props, pkField, tableId, tableId, false, dataSource);
				setBatchBtnsEnable.call(this, props, tableId);
				handleAlarmException.call(this, params, res, props, OperatorType, rows, content);
			} else {
				getScriptListReturn.call(this, params, res, props, pkField, tableId, tableId, false, dataSource);
				setBatchBtnsEnable.call(this, props, tableId);
			}
		}
	});
}

//处理预警异常信息
function handleAlarmException(params, res, props, OperatorType, rows, content) {
	let alarmMsgs = res.data.userMsgs;
	let alarmPks = new Set();
	for (let param of params) {
		if (alarmMsgs[param.id]) {
			alarmPks.add(param.id);
		}
	}
	//let resData = res.data.errorMsg.replace(new RegExp('<br/>', 'g'), '\n');
	let resData = res.data.errorMsg.split('<br/>');
	let jsx = '';
	jsx = resData.map((item, index) => {
		if (index == 0) {
			return;
		} else if (index == 1) {
			return (
				<div className={`alertMsg-space ${getThemeUtils() + 'theme'}`}>
					<div>
						<span className="iconfont icon-zhuyi1" />
					</div>
					<div>
						<p>{resData[0]}</p>
						<p>{resData[1]}</p>
					</div>
				</div>
			);
		} else {
			return (
				<div className={`${item.indexOf(alarmFlag) > 0 ? 'active' : ''} ${getThemeUtils() + 'theme'}`}>
					{item.replace(alarmFlag, '')}
				</div>
			);
		}
	});
	props.modal.show(alarmId, {
		content: jsx,
		beSureBtnClick: () => {
			commitAction.call(this, props, OperatorType, rows, content, alarmPks);
		}
	});
}

/**
 * 列表态 复写公共方法的回刷动作，为了预算异常单独处理
 */
export function selfListReturn(params, res, props, pk_bill, formId, tableId, isDelete, dataSource) {
	let pk = pk_bill;
	if (res.data.success === approveConst.HASAPPROVEALTRAN) {
		//指派信息
		let workflowData = res.data.approvealTranData;
		if (
			workflowData.workflow &&
			(workflowData.workflow == approveConst.APPROVEFLOW || workflowData.workflow == approveConst.WORKFLOW)
		) {
			if (params.length == 1) {
				props.table.selectAllRows(tableId, false); //先去掉之前勾选的行
				props.table.selectTableRows(tableId, [ params[0].index ], true);
				setBillFlowBtnsEnable.call(this, props, { tableId: tableId });
			}
			this.setState({
				compositedata: workflowData,
				compositedisplay: true
			});
		}
	} else {
		//数据回刷、缓存处理
		let Datas = res.data.cardVos;
		if (Datas != null) {
			let deleteIndexs = [];
			let updateIndexs = [];
			let successPk = []; //成功的pk
			//更新构造页面record
			Datas.map((v) => {
				let row = v.head[formId].rows[0].values;
				let index = queryArr(params, row[pk].value);
				let record = [
					{
						index,
						data: {
							status: '1',
							values: row
						}
					}
				];
				if (!isDelete) {
					props.table.updateDataByIndexs(tableId, record);
					updateIndexs.push(index);
				} else {
					deleteIndexs.push(index);
				}
				successPk.push(row[pk].value);
			});
			if (isDelete) {
				//删除页面数据
				props.table.deleteTableRowsByIndex(tableId, deleteIndexs);
				//删除缓存信息
				successPk.map((pk) => {
					props.table.deleteCacheId(tableId, pk);
				});
			} else {
				if (dataSource) {
					successPk.map((pk) => {
						cardCache.updateCache(pk_bill, pk, null, formId, dataSource);
					});
				}
				//设置成功的多选框不选中
				props.table.selectTableRows(tableId, updateIndexs, false, true);
			}
			//平台10-11晚上盘里会加入自动回调注册的绑定方法  之后这个可去掉
			setBillFlowBtnsEnable.call(this, props, { tableId: tableId });
		}
	}
}

//表体提交、收回
export function commitActionSignal(props, OperatorType, row) {
	commitAction.call(this, props, OperatorType, [ row ]);
}

//肩部的批量删除
function batchDelete(props) {
	let data = props.table.getCheckedRows(tableId);
	if (data.length == 0) {
		showMessage.call(this, props, { type: MsgConst.Type.ChooseDelete });
		return;
	}
	showConfirm.call(this, props, { type: MsgConst.Type.DelSelect, beSureBtnClick: deleteAction });
}

//表体行的单行删除
export function deleteLine(props, row) {
	deleteAction(props, [ row ]);
}

function deleteAction(props, rows) {
	let paramInfoMap = {};
	let params = '';
	//判断是表体还是表肩删除
	if (rows == null) {
		let data = props.table.getCheckedRows(tableId);
		params = data.map((v) => {
			let id = v.data.values.pk_newasset.value;
			let ts = v.data.values.ts.value;
			let index = v.index;
			paramInfoMap[id] = ts;
			return {
				id,
				index
			};
		});
	} else {
		params = rows.map((row) => {
			let id = row.values[pkField].value;
			let ts = row.values.ts.value;
			let index = row.index;
			paramInfoMap[id] = ts;
			return {
				id,
				index
			};
		});
	}
	ajax({
		url: url.DELETE,
		data: {
			paramInfoMap: paramInfoMap,
			dataType: 'listData',
			OperatorType: 'DELETE',
			pageid: pagecode
		},
		success: (res) => {
			getScriptListReturn(params, res, props, 'pk_newasset', tableId, tableId, true);
			setBatchBtnsEnable.call(this, props, tableId);
		}
	});
}

//刷新
function refreshAction(props) {
	batchRefresh.call(this, props, searchBtnClick);
}

/**
 * 设置批量按钮是否可用
 * @param {*} props 
 * @param {*} moduleId 
 */
export function setBatchBtnsEnable(props, moduleId) {
	setBillFlowBtnsEnable.call(this, props, { tableId: moduleId });
}

//普通url取值  ---  带?的
export function getUrlParamByPrivateUse(name) {
	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); //构造一个含有目标参数的正则表达式对象
	var params = null;
	if (window.location.search !== '') {
		params = window.location.search.substr(1).match(reg); //匹配目标参数
	} else {
		params = window.location.hash.substr(1).match(reg); //匹配目标参数
	}
	if (params != null) return params[2];
	return null; //返回参数值
}

/**
 * 跳转卡片
 * @param {*} props 
 * @param {*} record 
 */
export function linkToCard(props, record = {}, status) {
	props.pushTo(cardRouter, {
		status,
		id: record[pkField] ? record[pkField].value : '',
		pagecode: pagecode.replace('list', 'card')
	});
}

const queryArr = (params, item) => {
	for (var i = 0; i < params.length; i++) {
		if (params[i].id === item) return params[i].index;
	}
	return -1;
};

/*Hm9gUKDDwtNjV7Mk8onAzgXlk2sN3YqGeiNBfMPmEAaQ5tb/cjXQzjs3lVWuDzNj*/